// This file is a part of ChaosDB.
// Copyright (C) 2012 ChaoJianPeng
// email:chaojianpeng@gmail.com
//
// ChaosDB is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// ChaosDB is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

/*
 * monitor.cpp
 *
 *  Created on: 2012-4-18
 *      Author: chao
 */

#include "monitor.h"
#include <pthread.h>
#include <zmq.h>
#include "byte_array.h"
#include "cmalloc.h"
#include "cdb.h"

pthread_t mtid;
void *mctx, *mresponder;

void *monitor_thread(void *arg) {


	zmq_msg_t msg;

	while (1) {
		zmq_msg_init(&msg);
		zmq_recv(mresponder, &msg, 0);
		// 以后用于检查用户名之类的
		zmq_msg_close(&msg);

		// 发出去 当前内存占用 key数量
		zmq_msg_init_size(&msg, SIZE_INT * 3);
		*((long long*) zmq_msg_data(&msg)) = (long long) getUsed();
		*((int*) (zmq_msg_data(&msg) + SIZE_INT * 2)) = dbInfo();
		zmq_send(mresponder, &msg, 0);
		zmq_msg_close(&msg);
	}

	zmq_close(mresponder);

	return (void *) 0;
}

void startMonitor() {

	mctx = zmq_init(1);
	mresponder = zmq_socket(mctx, ZMQ_REP);

	zmq_bind(mresponder, "tcp://*:2333");
	pthread_create(&mtid, NULL, monitor_thread, NULL);
}

